Geospatial_03_exercise
import pandas as pd
import geopandas as gpd
import folium
from folium import Choropleth
from folium.plugins import HeatMap
from learntools.core import binder
binder.bind(globals())
from learntools.geospatial.ex3 import *
우리는 대화형 맵을 표시하기 위한 함수 'embed_map()'을 정의한다. 맵을 포함하는 변수와 맵을 저장할 HTML 파일의 이름이라는 두 가지 인수를 사용할 수 있습니다.
이 기능은 [모든 웹 브라우저에서] 지도를 볼 수 있도록 합니다(https://github.com/python-visualization/folium/issues/812).
def embed_map(m, file_name):
from IPython.display import IFrame
m.save(file_name)
return IFrame(file_name, width='100%', height='500px')
plate_boundaries = gpd.read_file("data/Plate_Boundaries/Plate_Boundaries/Plate_Boundaries.shp")
plate_boundaries['coordinates'] = plate_boundaries.apply(lambda x: [(b,a) for (a,b) in list(x.geometry.coords)], axis='columns')
plate_boundaries.drop('geometry', axis=1, inplace=True)
plate_boundaries.head()
그런 다음 변경 없이 아래의 코드 셀을 실행하여 과거 지진 데이터를 데이터 프레임 "지진"에 로드합니다.
earthquakes = pd.read_csv("data/earthquakes1970-2014.csv", parse_dates=["DateTime"])
earthquakes.head()
아래의 코드 셀은 지도에서 플레이트 경계를 시각화합니다. 지진 데이터를 모두 사용하여 동일한 지도에 열 지도를 추가하고 지진이 플레이트 경계와 일치하는지 여부를 확인합니다.
m_1 = folium.Map(location=[35,136], tiles='cartodbpositron', zoom_start=5)
for i in range(len(plate_boundaries)):
folium.PolyLine(locations=plate_boundaries.coordinates.iloc[i], weight=2, color='black').add_to(m_1)
# Your code here: Add a heatmap to the map
HeatMap(data=earthquakes[['Latitude', 'Longitude']], radius=15).add_to(m_1)
# Get credit for your work after you have created a map
q_1.a.check()
# Show the map
m_1
그렇다면, 위의 지도를 볼 때, 지진은 판 경계와 일치할까요?
q_1.b.solution()
m_2 = folium.Map(location=[35,136], tiles='cartodbpositron', zoom_start=5)
for i in range(len(plate_boundaries)):
folium.PolyLine(locations=plate_boundaries.coordinates.iloc[i], weight=2, color='black').add_to(m_2)
# Your code here: Add a map to visualize earthquake depth
def color_producer(val):
if val < 50:
return 'forestgreen'
elif val < 100:
return 'darkorange'
else:
return 'darkred'
for i in range(0,len(earthquakes)):
folium.Circle(
location=[earthquakes.iloc[i]['Latitude'], earthquakes.iloc[i]['Longitude']],
radius=2000,
color=color_producer(earthquakes.iloc[i]['Depth'])).add_to(m_2)
# Get credit for your work after you have created a map
q_2.a.check()
# View the map
m_2
플레이트 경계에 대한 근접성과 지진 깊이 사이의 관계를 탐지할 수 있습니까? 이 패턴이 전체적으로 유지됩니까? 일본에서요?
q_2.b.solution()
prefectures = gpd.read_file("data/japan-prefecture-boundaries/japan-prefecture-boundaries/japan-prefecture-boundaries.shp")
prefectures.set_index('prefecture', inplace=True)
prefectures.head()
다음 코드셀은 일본 각 도도부현의 인구, 면적(제곱킬로미터), 인구밀도(제곱킬로미터당)를 포함하는 데이터 프레임 '통계'를 생성한다. 코드 셀을 변경하지 않고 실행합니다.
population = pd.read_csv("data/japan-prefecture-population.csv")
population.set_index('prefecture', inplace=True)
# Calculate area (in square kilometers) of each prefecture
area_sqkm = pd.Series(prefectures.geometry.to_crs(epsg=32654).area / 10**6, name='area_sqkm')
stats = population.join(area_sqkm)
# Add density (per square kilometer) of each prefecture
stats['density'] = stats["population"] / stats["area_sqkm"]
stats.head()
다음 코드 셀을 사용하여 모집단 밀도를 시각화하는 맥락막 맵을 만듭니다.
m_3 = folium.Map(location=[35,136], tiles='cartodbpositron', zoom_start=5)
# Your code here: create a choropleth map to visualize population density
Choropleth(geo_data=prefectures['geometry'].__geo_interface__,
data=stats['density'],
key_on="feature.id",
fill_color='YlGnBu',
legend_name='Population density (per square kilometer)'
).add_to(m_3)
# Get credit for your work after you have created a map
q_3.a.check()
# View the map
# embed_map(m_3, 'q_3.html')
# m_3
어느 세 개의 현이 다른 현보다 상대적으로 밀도가 높습니까? 그들은 전국에 퍼져 있는가, 아니면 거의 같은 지리적 지역에 위치해 있는가? (일본 지리에 익숙하지 않은 경우 이 지도가 질문에 답하는 데 유용할 수 있습니다.
q_3.b.solution()
m_4 = folium.Map(location=[35,136], tiles='cartodbpositron', zoom_start=5)
# Your code here: create a map
def color_producer(magnitude):
if magnitude > 6.5:
return 'red'
else:
return 'green'
Choropleth(
geo_data=prefectures['geometry'].__geo_interface__,
data=stats['density'],
key_on="feature.id",
fill_color='BuPu',
legend_name='Population density (per square kilometer)').add_to(m_4)
for i in range(0,len(earthquakes)):
folium.Circle(
location=[earthquakes.iloc[i]['Latitude'], earthquakes.iloc[i]['Longitude']],
popup=("{} ({})").format(
earthquakes.iloc[i]['Magnitude'],
earthquakes.iloc[i]['DateTime'].year),
radius=earthquakes.iloc[i]['Magnitude']**5.5,
color=color_producer(earthquakes.iloc[i]['Magnitude'])).add_to(m_4)
# Get credit for your work after you have created a map
q_4.a.check()
# View the map
# m_4
추가 지진 보강을 위해 어느 현을 추천하십니까?
q_4.b.solution()
Keep going
Learn how to convert names of places to geographic coordinates with geocoding. You'll also explore special ways to join information from multiple GeoDataFrames.